﻿using Protobuf;
using System;
using UnityEngine;
using WebSocket4Net;
using PersonInfo;

public class ProtobufTest2 : MonoBehaviour
{
	// 服务器IP地址和端口号
	private string ServerAdress;

	// 玩家名字
	private string PlayName = "Aladdin";

	//发送的消息
	private string message;

	//接收到 服务器发回来的消息
	private string ServerMessage;

	public WebSocket websocket;

	void Start()
	{
		// 服务器IP地址和端口号
		ServerAdress = "ws://127.0.0.1:2014/";
		message = "Clients Send Message";
		ServerMessage = "Server Message";
	}

	void OnGUI()
	{
		//绘制2个 TxtBox文本输入框
		PlayName = GUI.TextField(new Rect(10, 10, 100, 20), PlayName);
		message = GUI.TextArea(new Rect(10, 40, 200, 200), message);
		ServerMessage = GUI.TextArea(new Rect(10, 250, 400, 200), ServerMessage);

		//连接到服务器
		if (GUI.Button(new Rect(250, 10, 150, 40), "Client连接"))
		{
			ConnectToServer();
		};

		if (websocket != null)
		{
			//测试向服务器发送消息
			if (GUI.Button(new Rect(250, 60, 150, 40), "SendMessageToServer"))
			{
				if (message.Length < 1 || PlayName.Length < 1)
					return;
				websocket.Send(ProtobufHelper.Serialize<Person>(new Person() { Name = this.PlayName, Gender = true, Msg = message }));
			};

			//断开连接按钮
			if (GUI.Button(new Rect(250, 120, 150, 40), "CloseSocket"))
			{
				websocket.Close();
				websocket = null;
			};
		}
	}

	private void ConnectToServer()
	{
		websocket = new WebSocket(ServerAdress);
		websocket.Opened += new EventHandler(websocket_Opened);
		websocket.Closed += new EventHandler(websocket_Closed);
		websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
		websocket.Open();
	}

	/// <summary>
	/// 连接上服务器
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void websocket_Opened(object sender, EventArgs e)
	{
		websocket.Send(PlayName + "Has Join The Game");
	}

	/// <summary>
	/// 接受连接
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
	{
		//TODO:这里要做消息分发处理，我这里就暂时默认服务器下发的就是Person的Protobuf的消息
		var personMsg = ProtobufHelper.DeSerialize<Person>(e.Message);
		ServerMessage += "Name:" + personMsg.Name + "  Gender:" + personMsg.Gender + "  Info:" + personMsg.Msg + "\n";
	}

	/// <summary>
	/// 断开连接
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void websocket_Closed(object sender, EventArgs e)
	{
		websocket.Close();
	}
}